﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RuleOfReady.Core.Utility
{
    public static class CollectionExtensions
    {

        private static readonly ThreadSafeRandom random = new ThreadSafeRandom();


        /// <summary>
        /// In place shuffle of a list (based on Fisher-Yates shuffle)
        /// </summary>
        /// <typeparam name="T">type of list to shuffle</typeparam>
        /// <param name="list">list to shuffle</param>
        public static void Shuffle<T>(this IList<T> list)
        {
            int shuffleToIdx = list.Count;
            while (shuffleToIdx > 1)
            {
                shuffleToIdx -= 1;
                int shuffleFromIdx = random.Next(shuffleToIdx + 1);
                T value = list[shuffleFromIdx];
                list[shuffleFromIdx] = list[shuffleToIdx];
                list[shuffleToIdx] = value;
            }
        }

        /// <summary>
        /// Removes and returns the first element of the list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static T PopFirst<T>(this LinkedList<T> list)
        {
            if (list == null || !list.Any())
                return default(T);

            T element = list.First.Value;
            list.RemoveFirst();
            return element;
        }

        /// <summary>
        /// Removes and returns the first element of the list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static T PopLast<T>(this LinkedList<T> list)
        {
            if (list == null || !list.Any())
                return default(T);

            T element = list.Last.Value;
            list.RemoveLast();
            return element;
        }
    }
}
